<?php

class sfDatagrid2WidgetDoctrineDatagrid extends sfDatagrid2WidgetDatagrid {
	
	protected $currentRecord;
	
	/**
	 * Configures the current widget.
	 *
	 * Available options:
	 *
	 * * model:       	Name of model
	 * * coll:			corresponding Doctrine_Collection
	 *
	 * @param array $options     An array of options
	 * @param array $attributes  An array of default HTML attributes
	 *
	 * @see sfDatagrid2WidgetDatagrid
	 */
	protected function configure($options = array(), $attributes = array()) {
		parent::configure($options, $attributes);
		
		$this->addRequiredOption( 'model' );
		$this->addRequiredOption('coll');
		
		if(!(Doctrine_Core::getTable($options['model']) instanceof Doctrine_Table)) {
			throw new InvalidArgumentException("Model '".$options['model']."' not found");
		}
		
		if(!($options['coll'] instanceof Doctrine_Collection)) {
			#throw new InvalidArgumentException('Coll option must be instance of Doctrine_Collection, '.get_class($options['coll']).' given.');
		}
	}
	
	protected function renderTableBody() {
		$columns = $this->getOption('columns');
		
		$rows = '';
		
		foreach($this->getOption('coll') as $i => $item) {
			$cells = '';
			foreach($columns as $label => $binding) {
				$cells .= $this->renderContentTag('td', $this->parseBinding($binding, $item));
			}
			$rows.= $this->renderBodyRow($cells, $i);
		}
		return $this->renderContentTag('tbody', $rows);
	}
	
	protected function parseBinding($binding, $record) {
//		if($this->getTable()->hasColumn($binding)) {
//			return $record->get($binding);
//		} else {
//			return $binding;
//		}
		$this->currentRecord = $record;
		return preg_replace_callback('/\#\#(\w+)\#\#/', array($this, 'parseBindingCallback'), $binding);
	}
	
	private function parseBindingCallback($matches) {
		return $this->currentRecord->get($matches[1]);
	}
	
	/**
	 * @return Doctrine_Table
	 */
	protected function getTable() {
		return Doctrine_Core::getTable($this->getOption('model'));
	}
}